var util=require('util');
var database=require('../config/database.json');
var host=database.host;
var db=database.db;
var mongodb=require('../DAOImpl/mongodb.js');
var mon1=new mongodb(host,db);
var status=require('../config/status.json');

/*
 *  @req.query: origin,destination,sensor(optional)
 */
function getDistance(req, res, next) {
	var google = require('../private/googleService/service');
	console.log(req.query);
	google.getDistance(req.query, function(err, data){
		if (!err) {
			var result = {
				'resultCode' : 0,
				'distance' : data.routes[0].legs[0].distance,
				'duration' : data.routes[0].legs[0].duration
			};
			res.send(result);
		} else {
			var result = {
				'resultCode' : -1
			};
			res.send(result);
		}
	});
	var client = require("../DAOImpl/mongodb");
	var c = new client();
	c.insert();
	return next;
}

/*
 * @req.body: cus_id 
 * {'cus_id': '1'}
 */
function waiting(req, res, next){
	var query2=new Object();
	var result=new Object();
	var query={
		"id":req.body.cus_id	
	};
	mon1.findOne(database.col_customer,query,function(err1,err2,doc){	
		query2.latitude=doc.latitude;
		query2.longitude=doc.longitude;
		mon1.find(database.col_driver,query2,function(err3,err4,doc1){
			if(err1||err2||err3||err4){
				result.status=status.SHOWORDER.FAIL
			}else{
				if(doc1){
			    	result.status=status.WAITING.SUCCESS
					}
					else{
						result.status=status.WAITING.NO_MATCH
					}
				console.log(result);
				res.send(result);
			}
		});
	});
	res.send(result);
	return next;
}

/*
 * @req.body: cus_id
 * {{'cus_id': '1'}}
 */

function cancelRequest(req, res, next){
	
	
	var result ={'resultCode': 0};
	res.send(result);
	return next;
}
/*
 * @req.body: cus_id
 * {'cus_id': '1'}
 */

function showCustomer(req, res, next){
	var result=new Object();
	var query={
			"id":req.body.cus_id
	}
	mon1.findOne(database.col_customer,query,function(err1,err2,doc){
	//	console.log(doc);
		if(err1||err2){
			result.status=status.SHOWCUSTOMER.FAIL;
			console.log("err");
		}else{
			
			result.status=status.SHOWCUSTOMER.SUCCESS;
			result.cus_info = new Object();
			result.cus_info.id=doc.id;
			result.cus_info.phone=doc.phone;
			result.cus_info.credit=doc.credit;
			result.cus_info.photo=doc.photo;
			console.log(doc);
			res.send(result);
		}	
	});
	return next();
}
exports.services = [ getDistance, waiting, cancelRequest, showCustomer];